//
//  SaveScoreLayer.m
//  Asteroids
//
// This class will implement a cocos2d-iphone layer that will show the
// names and high scores associated with the device, and allow the user
// to enter a new name for the device. 
//
// Created by Charles Kollar charles@kollar.com on 11/8/10 to serve as a
// "starter" app for an iPod/iPhone/iPad programming course.
//
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#import "SaveScoreLayer.h"
#import "AsteroidsLayer.h"
#import "DetailOverlayLayer.h"
#import "ApplicationData.h"


@implementation SaveScoreLayer

@synthesize localUsers;
@synthesize addButton;
@synthesize oglView;
@synthesize userTable;
@synthesize ignoreInput;

//
// UI methods...
//


// These next three methods handle the input of a name to the userlist
// when the user presses the 'adduser' button....
//
// Here we will create a UIAlertView with two buttons (Add, and Cancel).
// We attach a UITextView to it to give the user somewhere to type the name.
// We make it 'first responder' so that it immediately begins taking input.
// If the user clicks 'Cancel' we don't want to add the stirng entered
// in the UITextView into our list of users. So we need to implement some
// logic to keep this from happening. We implement the
// UIAlertViewDelegate protocol method alertView:clickedButtonAtIndex to
// keep track of which button was pressed (N = 0 for Cancel, N = 1 for Add).
// If the 'Cancel' button was pressed we set the boolean 'ignoreInput' to
// true. We check this boolean in the UITextField extFieldDidEndEditing handler
// to determine whether or not to ignore the input

//
// Established as the controller for button presses in the init method
// using the UIControl method addTarget:action:forControlEvents on event
// UIContolEventTouchUpInside
- (void)addUserButtonEvent:(id) __attribute__ ((unused)) sender
{
    UIAlertView* myAlertView =
	[[UIAlertView alloc] initWithTitle: @"Please enter your name"
							   message: @"\n"     // just make space for the text view
							  delegate: self 
					 cancelButtonTitle: @"Cancel" // index = 0
					 otherButtonTitles: @"Add",   // index = 1
	 nil];
    [oglView addSubview: myAlertView];
    
	// Create a text field to collect user input in...
    UITextField* userNameTextField = [[UITextField alloc] initWithFrame: CGRectMake(12.0, 35.0, 260.0, 30.0)];
    userNameTextField.delegate = self; // set this layer as the UITextFieldDelegate
    [userNameTextField setBackgroundColor: [UIColor whiteColor]];
	
	// Add the text field to the alert view...
    [myAlertView addSubview: userNameTextField];
    [myAlertView show];
    [myAlertView release];

	// Assume that the user will want the data that they entered in the text field...
	ignoreInput = NO;
	
	// This causes the text field to be 'selected' so to speak...
	[userNameTextField becomeFirstResponder];
}

// Implement the UIAlertViewDelegate protocol method alertView:clickedButtonAtIndex
// To tell us when the user clicks a button on our UIAlertView, and what the button was.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonN
{
	NSLog(@"alertView:clickedButtonAtIndex N: %d\n", buttonN);
	// buttonN == 0 is the Cancle button...
	// Flag the tetFieldDidEndEditing method below to ignore it's input...
	if (buttonN == 0) ignoreInput = YES;
}

// This method is called after the text field resigns its first responder status.
// You can use this method to update your delegate’s state information.
- (void)textFieldDidEndEditing:(UITextField *)textField {
	if (ignoreInput == YES) {
		NSLog(@"textFieldDidEndEditing Ignoring input!\n");
		return;
	}
	
    NSString *userNameAdded = [textField text];
	NSLog(@"textFieldDidEndEditing name: %@\n", userNameAdded);
	
    // add this user name to the list in the table
    [localUsers addObject: userNameAdded];  
    [userTable reloadData];
	
    // add this user name to the application data <name, score> information...
    [[ApplicationData shared] addUser:userNameAdded];
}


//
// UITableViewDataSource protocol methods...

// protocol UITableView:numberOfSectionsInTableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *) __attribute__ ((unused)) tableView {
    return 1;
}

// protocol UITableView:numberOfRowsInSection (REQUIRED METHOD)
- (NSInteger)tableView:(UITableView *) __attribute__ ((unused)) tableView numberOfRowsInSection:(NSInteger) __attribute__ ((unused)) section {
	return [localUsers count];
}

// protocol IUTableView:titleForHeaderInSection
- (NSString *)tableView:(UITableView *) __attribute__ ((unused)) tableView titleForHeaderInSection:(NSInteger) __attribute__ ((unused)) section {
    return @"Select User";
}

// protocol UITableView:cellForRowAtIndexPath (REQUIRED METHOD)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
				initWithStyle:UITableViewCellStyleDefault
				reuseIdentifier:MyIdentifier];
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }

	// just print the key (name)
	//cell.textLabel.text = [localUsers objectAtIndex:[indexPath row]];
	// Print the key and the score...
	NSString *key = [localUsers objectAtIndex:[indexPath row]];
	cell.textLabel.text = key;
    return cell;
}

//
// UITableViewDelegate protocol methods...

// These next two methods are called when the user clicks on one row or another.
// If a row had been previously selected then the 'deselect' method is called.
// If the row was never selected or the user clicks on the same row then the
// deselect method is not called

// protocol UITableViewDelegate:didSelectRowAtIndexPath (management method)
- (void)tableView:(UITableView*) __attribute__ ((unused)) tableView didSelectRowAtIndexPath:(NSIndexPath *) __attribute__ ((unused)) indexPath {
    NSLog(@"tableView didSelectRowAtIndexPath i: %d\n", [indexPath row]);
}

// protocol UITableViewDelegate:didDeselectRowAtIndexPath (management method)
- (void)tableView:(UITableView*) __attribute__ ((unused)) tableView didDeselectRowAtIndexPath:(NSIndexPath *) __attribute__ ((unused)) indexPath {
    NSLog(@"ableView didDeselectRowAtIndexPath i: %d\n", [indexPath row]);
}

//
// Create the SaveScoreLayer screen on an openGLView...
// Add an 'add user' button which when clicked will popup a dialog for the
// user to add a username to the names list for the device.
// Also add a table that will show the list of usernames that have been added
// on the current device.
// Before populating the table, we get the userlist (including their high score
// from the application property list for this device...

- (id)init
{ 
	if ((self=[super init])) {
		localUsers = [[ApplicationData shared] getLocalUsers];
		
		// This is important if we get here after the game has started...
		[[ApplicationData shared] reset];
		
		oglView = [[CCDirector sharedDirector] openGLView];
        
        CGRect frame4 = CGRectMake(10.0, 40.0, 100.0, 30.0);
        addButton = [[UIButton alloc] initWithFrame:frame4];
        UIImage *buttonImage = [UIImage imageNamed:@"btn-adduser-normal.png"];
        [addButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
        buttonImage = [UIImage imageNamed:@"btn-adduser-selected.png"];
        [addButton setBackgroundImage:buttonImage forState:UIControlStateSelected];
        addButton.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        addButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
		
		// addTarget:action:forConrolEvents is a UIControl Class method
		// UIButton inherits from... UIControl : UIView : UIResponder : NSObject
        [addButton addTarget:self
                      action:@selector(addUserButtonEvent:) 
            forControlEvents:UIControlEventTouchUpInside];
        // then add the button to a UIView....
        [oglView addSubview: addButton];
		// The inverse of this method is 'removeFromSuperview'
        
		// The first pair are the top left hand point of the box...
        CGRect frame3 = CGRectMake(40, 200, 220, 240);
        userTable = [[UITableView alloc] initWithFrame:frame3 style:UITableViewStylePlain];
        userTable.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        userTable.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        userTable.delegate = self;
        userTable.dataSource = self;
        [oglView addSubview: userTable];
		
        [userTable reloadData];
    }
    return self;
}

- (void)dealloc
{
	NSLog(@"SaveScoreLayer dealloc\n");
	// Since we will not be around to use these items, release them so that
	// they may be garbage colleted...
    [localUsers release];
	[addButton release];
	// Important NOTE: Since there is only one OpenGLView, you should NOT release it here!
	[userTable release];
    
    [super dealloc];
}

@end
